﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using PIMS.Base;
using PIMS.DBModel;
using PIMS.Interface;
using PIMS.WorkPlugin.ORM;
using PIMS.WorkPlugin.WMS;
using PIMS.XmlModel;
using PIMS.YongXiang;
using PIMS_Interface.Interface;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;

namespace PIMS.WorkPlugin
{
    public class CE24056_PalletizerHandle : IPLCSignalHandle, IDisposable
    {
        private IDebugMsg debug = null;
        ICommunication plc = null;
        ILog4net log = null;
        int plcIndex = -1;
        int lineCount = 2;
        bool heartBeat = false;
        //bool bWriteBox = true;

        /// <summary>
        /// PLC输入信号例子，每个输入信号要配套一个PLCSignalHandle
        /// </summary>
        //private PLCSignalHandle x1 = null;
        private PLCSignalHandle p1 = null;//码垛完成

        CancellationTokenSource cancelTokenSource = new CancellationTokenSource();
        bool alive = false;
        bool eBoxLock = false;

        /// <summary>
        /// wms地址
        /// </summary>
        private string _httpUrl = "http://10.9.68.2:9998/dataSyncApi/interfaceapi/ProductionInformation";//接口地址：http://ip:port/com.ksec.l2260.erpif/jbaprpc/mes/receipt

        #region pal实现日志分组功能
        private void DebugMsg(string Msg, InfoLevel level = InfoLevel.info)
        {
            debug.DebugMsg(Msg, LogGroup.pal, level);
        }

        private void LogInfo(string message)
        {
            log.Info(message, LogGroup.pal, plcIndex + 1);
        }

        private void LogError(string message)
        {
            log.Error(message, LogGroup.pal, plcIndex + 1);
        }

        private void LogError(string message, Exception ex)
        {
            log.Error(message, LogGroup.pal, plcIndex + 1, ex);
        }
        #endregion

        public void Init(ICommunication plc, int plcIndex, IDebugMsg debugMsg, ILog4net log4net, PIMSConfigX config)
        {
            this.plc = plc;
            this.plcIndex = plcIndex;
            this.debug = debugMsg;
            this.log = log4net;

            p1 = new PLCSignalHandle(PAL.写入通知, EventId.码垛完成, debug, this.log);
            if (!p1.EventBindOk)
            {
                //给输入信号绑定事件
                p1.msgHandler += new PLCSignalHandle.MsgHandler(EventHandleP);
            }

            new Task(Thread_CommicationPLC, cancelTokenSource.Token).Start();

            DebugMsg(String.Format("CE24056_PalletizerHandle{0} 挂载成功！", this.plcIndex));
            LogInfo(String.Format("CE24056_PalletizerHandle{0} 挂载成功！", this.plcIndex));

            string zero = "".PadRight(50, '0');
        }

        public void Dispose()
        {
            try
            {
                cancelTokenSource.Cancel();
            }
            catch
            {
            }
        }

        private void Thread_CommicationPLC()
        {
            string oldMsg = "";
            while (!cancelTokenSource.IsCancellationRequested)
            {
                try
                {
                    if (plc.IsConnected)
                    {
                        if (!alive)
                        {
                            alive = true;
                            this.DebugMsg(plc.GetDeviceName() + "连接成功！", InfoLevel.info);
                            this.LogInfo(plc.GetDeviceName() + "连接成功！");
                        }
                        HandleCycle();
                    }
                    else
                    {
                        alive = false;
                        Thread.Sleep(1000);
                        plc.Connect();
                    }
                }
                catch (Exception ex)
                {
                    if (oldMsg != ex.Message)
                    {
                        oldMsg = ex.Message;
                        this.DebugMsg(oldMsg, InfoLevel.error);
                        this.LogError(oldMsg, ex);
                    }

                    plc.DisConnect();
                }
                Thread.Sleep(300);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="plc"></param>
        /// <param name="index"></param>
        public void HandleCycle()
        {
            if (plc.IsConnected)
            {
                this.heartBeat = !this.heartBeat;
                this.plc.Write(PAL.上位机心跳, this.heartBeat);

                p1.CheckSignal(plc, plcIndex);

                bool result1, result2;
                //复位下发包装重量信号
                if (!this.plc.Read<bool>(PAL.写入通知, out result1) && this.plc.Read<bool>(PAL.接收数据成功, out result2))
                {
                    if (result1 && result2)
                    {
                        this.plc.Write(PAL.接收数据成功, false);
                        this.DebugMsg("复位 入库完成信号");
                        this.LogInfo("复位 入库完成信号");
                    }
                }
            }
        }


        private void EventHandleP(PlcSignalPara para)
        {
            new Thread(new ParameterizedThreadStart(Thread_HandleEventP)) { IsBackground = true }.Start(para);
        }

        /// <summary>
        /// PLC编号从0开始
        /// </summary>
        /// <param name="obj"></param>
        private void Thread_HandleEventP(object obj)
        {
            try
            {
                PlcSignalPara p = (PlcSignalPara)obj;

                //DateTime now = DateTime.Now;
                //this.LogInfo($"* PLC编号={p.plcIndex},触发事件ID={p.eventId.ToString()}");
                //this.DebugMsg(now.ToString() + "开始！");
                //this.LogInfo(now.ToString() + "开始！");
                Thread.Sleep(50);
                switch (p.eventId)
                {
                    case EventId.码垛完成:
                        {
                            bool rFlag1 = false;
                            bool rFlag2 = false;
                            int count = 0;

                            int bagCount = 0;
                            ///芯片id
                            byte[] chipID = null;
                            string chipIDstr = "";
                            ///芯片内容
                            //byte[] chipContent = null;
                            string chipContentstr = null;
                            int lineNO = 0;

                            while (count < 10)
                            {

                                bagCount = this.plc.Read<int>(PAL.袋数, out rFlag2);
                                chipID = this.plc.Read<byte[]>(PAL.芯片ID, out rFlag1);
                                chipID = chipID.Skip(0).Take(12).ToArray();     
                                //chipContent = this.plc.Read<byte[]>(PAL.芯片内容, out rFlag2);                      
                                if (rFlag1 && rFlag2)// && rFlag3
                                {
                                    break;
                                }
                                else if (count >= 9)
                                {
                                    if (!rFlag1)
                                    {
                                        this.DebugMsg("读取托盘条码信息超时！", InfoLevel.error);
                                        this.LogError("读取托盘条码信息超时！");
                                        return;
                                    }
                                    if (!rFlag2)
                                    {
                                        this.DebugMsg("读取料袋数量信息超时！", InfoLevel.error);
                                        this.LogError("读取料袋数量信息超时！");
                                        return;
                                    }
                                    //if (!rFlag3)
                                    //{
                                    //    this.DebugMsg("产线号读取超时！", InfoLevel.error);
                                    //    this.LogError("产线号读取超时！");
                                    //    return;
                                    //}
                                }
                                count++;
                                Thread.Sleep(200);
                            }

                            for (int i = 0; i < chipID.Length; i++)
                            {
                                chipIDstr += Convert.ToString(chipID[i], 16);
                            }
                            var RFID = ConvertHexAsciiToString(chipIDstr).Substring(0,6);
                            //for (int i = 0; i < chipContent.Length; i++)
                            //{
                            //    chipContentstr += Convert.ToString(chipID[i], 16);
                            //}

                            //onlyNos = ByteArrayToString(onlyNo);
                            //chipIDstr = chipIDstr.Trim().ToUpper();
                            this.DebugMsg($"读取托盘ID:{RFID}/袋数{bagCount}/plcIndex{plcIndex}");
                            //this.LogError($"读取托盘ID:{RFID}/袋数{bagCount}/plcIndex{plcIndex}");

                            #region 获取对应产线订单
                            //plc0对应1产线   plc1对应2产线
                            
                            //根据PLC编号与产线对应关系取到相应的产线工单
                            List<orderformcurrent> currentList = SqlSugarHelper.GetDb().Queryable<orderformcurrent>().Where(s=> s.id.Equals(plcIndex + 1) && s.sendToPLC == "1").ToList();
                            if (currentList == null || currentList.Count == 0)
                            {
                                this.DebugMsg($"{p.plcIndex + 1}对应的产线工单无效！", InfoLevel.error);
                                this.LogError($"{p.plcIndex + 1}对应的产线工单无效！");
                                return;
                            }
                            orderformcurrent current = currentList[0];
                            lineNO = current.id;
                            #endregion
                            
                            saveddata save = null;
                            if (!String.IsNullOrEmpty(current.batchNo))
                            {
                                //工单有效
                                save = new saveddata(current);
                            }
                            else
                            {
                                this.DebugMsg($"{lineNO}号线对应的产线工单为空！", InfoLevel.warring);
                                this.LogError($"{lineNO}号线对应的产线工单为空！");

                                //产线工单为空时，取最近的历史工单
                                orderformhistory history = SqlSugarHelper.QueryOrderByDesc<orderformhistory>(n => n.line == lineNO, n => n.finishTime);
                                if (history != null)
                                {
                                    save = new saveddata(history);
                                }
                                else
                                {
                                    this.DebugMsg($"{lineNO}号线对应的历史工单无效！", InfoLevel.error);
                                    this.LogError($"{lineNO}号线对应的历史工单无效！");
                                    return;
                                }
                            }

                            if (save != null)
                            {
                                save.line = lineNO;//==1?"产线A":"产线B";
                                save.uid = RFID;
                                save.count = bagCount.ToString();   //袋数*25kg/袋   naniand=重量
                                decimal weight = (decimal)bagCount * 25 / 1000;
                                save.weight = weight.ToString();
                                save.productTime = DateTime.Now;

                                Msg_WMS wmsInfo = new Msg_WMS();
                                wmsInfo.weight = weight;  //袋数*25
                                wmsInfo.palletNo = save.uid;
                                wmsInfo.requestId = Guid.NewGuid().ToString();
                                wmsInfo.locNo = current.id.ToString();
                                wmsInfo.orderNo =save.workOrder;
                                wmsInfo.brand = save.grade;
                                //wmsInfo.MaterNo = save.productMark;
                                //wmsInfo.MaterName = save.productName;
                                wmsInfo.batchNo = save.batchNo;
                                wmsInfo.productionTime = save.productTime.ToString("yyyy-MM-dd HH:mm:ss");
                                wmsInfo.isFull = bagCount==40 ?1:0;//袋数?=40;
                                if (save.reserved2.Contains("木"))
                                    wmsInfo.wrapper = 0;
                                else if (save.reserved2.Contains("塑"))
                                    wmsInfo.wrapper = 1;

                                if (save.reserved3.Equals("待检"))
                                    wmsInfo.productGrade = 1;
                                else if (save.reserved3.Contains("合格品"))
                                    wmsInfo.productGrade = 2;
                                else if (save.reserved3.Contains("客户合格品"))
                                    wmsInfo.productGrade = 3;
                                else if (save.reserved3.Contains("优等品"))
                                    wmsInfo.productGrade = 4;
                                else if (save.reserved3.Contains("不合格"))
                                    wmsInfo.productGrade = 99;


                                if (save.reserved4.Equals("生产入库"))
                                    wmsInfo.productType = 1;
                                else if (save.reserved4.Contains("退货入库"))
                                    wmsInfo.productType = 2;

                                ////实时读取，不能用订单的
                                //wmsInfoItem.HSBA011 = save.reserved5;
                                //wmsInfoItem.HSBA012 = save.batchNo;
                                //wmsInfo.ZZDHH = save.workOrder;

                                string msg = JsonConvert.SerializeObject(wmsInfo);
                                //this.log.Info(msg);
                                var mesResult = WMSHttp.HttpPost(_httpUrl, msg);
                                Msg_WMS_Return msg_WMS_Return = (Msg_WMS_Return)JsonConvert.DeserializeObject<Msg_WMS_Return>(mesResult);
                                if (msg_WMS_Return.ErrCode == "0")
                                {
                                    this.debug.DebugMsg($"{save.packager}包装线自动入库成功!唯一码{save.uid},批次号{save.batchNo}");
                                    this.log.Info($"{save.packager}包装线自动入库成功!唯一码{save.uid},批次号{save.batchNo}");
                                    SqlSugarHelper.InsertRecord<saveddata>(save);
                                    this.debug.DebugMsg($"{save.packager}包装线添加生产记录,唯一码{save.uid},批次号{save.batchNo},包数{save.count}");
                                    this.log.Info($"{save.packager}包装线添加生产记录,唯一码{save.uid},批次号{save.batchNo},包数{save.count}");
                                }
                                else
                                {
                                    this.debug.DebugMsg($"{save.packager}包装线自动入库失败！返回信息：{msg_WMS_Return.ErrMess}  接口报文：{msg}", InfoLevel.error);
                                    this.log.Error($"{save.packager}包装线自动入库失败！返回信息：{msg_WMS_Return.ErrMess}  接口报文：{msg}");
                                }
                                    
                            }
                            
                            count = 0;
                            while (count < 10)
                            {
                                count++;
                                if (this.plc.Write<bool>(PAL.接收数据成功, true))
                                {
                                    this.DebugMsg("置位 上位机完成反馈");
                                    this.LogInfo("置位 上位机完成反馈");
                                    break;
                                }
                                Thread.Sleep(200);
                            }
                            break;
                        }
                    default:
                        throw new Exception($"无法识别的事件ID {p.eventId.ToString()}");
                }
            }
            catch (Exception ex)
            {
                this.LogError("", ex);
                this.DebugMsg(ex.Message, InfoLevel.error);
            }
        }

        public static string ByteArrayToString(byte[] b)
        {
            string result = "";
            int count = 0;
            for (int i = 0; i < b.Length; i++)
            {
                if (b[i] != 0)
                    count++;
                else
                    break;
            }
            if (count == 0) return "";
            byte[] b2 = new byte[count];
            Array.Copy(b, b2, count);
            result = Encoding.UTF8.GetString(b2);
            return result;
        }


        /// <summary>
        /// 将十六进制ASCII码字符串转换为对应的字符串
        /// </summary>
        /// <param name="hexAscii">十六进制ASCII码字符串</param>
        /// <returns>转换后的字符串</returns>
        public static string ConvertHexAsciiToString(string hexAscii)
        {
            if (string.IsNullOrEmpty(hexAscii))
                return string.Empty;

            if (hexAscii.Length % 2 != 0)
                throw new ArgumentException("十六进制ASCII字符串长度必须为偶数");

            StringBuilder result = new StringBuilder();

            // 每两个字符为一组，转换为一个字节
            for (int i = 0; i < hexAscii.Length; i += 2)
            {
                string hexByte = hexAscii.Substring(i, 2);
                int asciiCode = Convert.ToInt32(hexByte, 16); // 16表示十六进制
                result.Append((char)asciiCode);
            }

            return result.ToString().Trim();
        }

        #region 用不到

        /// <summary>
        /// 按每袋10Kg计算总重
        /// </summary>
        /// <param name="fullCount"></param>
        /// <returns></returns>
        private string GetFullWeight(string fullCount)
        {
            int count;
            int.TryParse(fullCount, out count);
            return (count * 10).ToString();
        }

        /// <summary>
        /// 打印60袋信息到日志
        /// </summary>
        /// <param name="list"></param>
        private void Print60BagsInfo(List<string> list)
        {
            string msg = "";
            for (int i = 0; i < list.Count; i++)
            {
                msg += list[i] + " ";
                if ((i + 1) % 15 == 0)
                {
                    LogInfo(msg);
                    msg = "";
                }
            }
            if (msg != "")
            {
                LogInfo(msg);
            }
        }

        ///// <summary>
        ///// 保存流水号及箱号
        ///// </summary>
        ///// <param name="lineNum"></param>
        ///// <param name="water"></param>
        ///// <param name="boxId"></param>
        //private void SaveBoxIdAndWater(string lineNum, int water, string boxId)
        //{
        //    try
        //    {
        //        SqlSugarHelper.DeleteRecord<BoxIdAndWater>($"water='{water.ToString()}' and line='{lineNum}'");

        //        BoxIdAndWater w = new BoxIdAndWater();
        //        w.water = water;
        //        w.line = lineNum;
        //        w.boxid = boxId;
        //        w.createTime = DateTime.Now;
        //        SqlSugarHelper.InsertRecord<BoxIdAndWater>(w);
        //    }
        //    catch (Exception ex)
        //    {
        //        this.LogError(ex.Message, ex);
        //    }
        //}

        ///// <summary>
        ///// 查询流水号对应的箱号
        ///// </summary>
        ///// <param name="lineNum"></param>
        ///// <param name="water"></param>
        ///// <returns></returns>
        //private string GetBoxIdByWater(string lineNum, int water)
        //{
        //    string boxId = "";
        //    try
        //    {
        //        string cmdSql = string.Concat(new string[]
        //       {
        //         "select * from 流水箱号转换表 where water='",
        //          water.ToString(),
        //          "' and line='",
        //          lineNum,
        //          "'"
        //       });
        //        DataTable dt = SqlSugarHelper.QueryToDataTable<BoxIdAndWater>(cmdSql);
        //        if (dt != null && dt.Rows.Count > 0)
        //        {
        //            boxId = dt.Rows[0]["boxid"].ToString();
        //        }
        //        else
        //        {
        //            return "";
        //        }

        //    }
        //    catch (Exception ex)
        //    {
        //        this.LogError(ex.Message, ex);
        //        return "";
        //    }
        //    return boxId;
        //}

        ///// <summary>
        ///// 删除使用过的箱号
        ///// </summary>
        ///// <param name="boxId"></param>
        //private void DeleteBoxIdAndWater(string boxId)
        //{
        //    try
        //    {
        //        SqlSugarHelper.DeleteRecord<BoxIdAndWater>($"boxid='{boxId}'");
        //    }
        //    catch (Exception ex)
        //    {
        //        this.LogError(ex.Message, ex);
        //    }
        //}

        //private void DeleteBoxIdAndWater(string lineNum, int water)
        //{
        //    try
        //    {
        //        SqlSugarHelper.DeleteRecord<BoxIdAndWater>($"line='{lineNum}' and water='{water}'");
        //    }
        //    catch (Exception ex)
        //    {
        //        this.LogError(ex.Message, ex);
        //    }
        //}

        //private bool CheckBoxScanInfo(string boxBarcode)
        //{
        //    if (String.IsNullOrEmpty(boxBarcode))
        //    {
        //        this.DebugMsg("箱标为空！", InfoLevel.error);
        //        return false;
        //    }
        //    try
        //    {
        //        saveddata box = SqlSugarHelper.QueryOrderByDesc<saveddata>(n => n.uid == boxBarcode, m => m.productTime);
        //        if (box != null)
        //        {
        //            if (box.reserved9 == "1") //扫描仪反馈
        //            {
        //                this.DebugMsg("箱标重复" + boxBarcode, InfoLevel.error);
        //                this.LogInfo("箱标重复" + boxBarcode);
        //                return false;
        //            }
        //            box.reserved9 = "1"; //扫描仪反馈
        //            SqlSugarHelper.UpdateRecord<saveddata>(box);
        //            return true;
        //            //if (box.count.Equals("60"))
        //            //    return true;
        //            //else if(box.reserved13.Equals("1"))
        //            //{
        //            //    this.DebugMsg("半箱强排" + boxBarcode, InfoLevel.warring);
        //            //    this.LogInfo("半箱强排" + boxBarcode);
        //            //    return true;
        //            //}
        //            //else
        //            //{
        //            //    this.DebugMsg("半箱下线" + boxBarcode, InfoLevel.warring);
        //            //    this.LogInfo("半箱下线" + boxBarcode);
        //            //    return false;
        //            //}

        //        }
        //        else
        //        {
        //            this.DebugMsg("数据库中无此箱标记录" + boxBarcode, InfoLevel.error);
        //            this.LogError("数据库中无此箱标记录" + boxBarcode);
        //            return false;
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        this.LogError(ex.Message, ex);
        //        return false;
        //    }
        //}

        ///// <summary>
        ///// 依玛仕贴标数据生成
        ///// 使用 依玛仕箱标配置.xml
        ///// </summary>
        ///// <param name="boxBarcode"></param>
        ///// <returns></returns>
        //private string GeneralBoxPrintInfoFromXml(string boxBarcode, out string type)
        //{
        //    type = "";
        //    if (String.IsNullOrEmpty(boxBarcode))
        //    {
        //        this.DebugMsg("箱标为空！", InfoLevel.error);
        //        return "";
        //    }
        //    string boxPrintInfo = "";
        //    string cmdSql = string.Concat(new string[]
        //       {
        //         "select * from tb_saveddata where uid='",
        //          boxBarcode,
        //          "'"
        //       });
        //    try
        //    {
        //        DataTable dtBox = SqlSugarHelper.QueryToDataTable<saveddata>(cmdSql);
        //        if (dtBox != null && dtBox.Rows.Count > 0)
        //        {
        //            string xmlPath = AppDomain.CurrentDomain.BaseDirectory + "config\\依玛仕箱标配置.xml";
        //            XmlDocument xmlDocument = new XmlDocument();
        //            XmlReaderSettings settings = new XmlReaderSettings();
        //            settings.IgnoreComments = true;
        //            XmlReader reader = XmlReader.Create(xmlPath, settings);
        //            xmlDocument.Load(reader);
        //            XmlNodeList nodeList = xmlDocument.GetElementsByTagName("字段");
        //            reader.Close();

        //            string separator = nodeList[0].Attributes["分隔符"].Value.Replace("/r/n", Environment.NewLine); //\r\n
        //            bool mark = false;
        //            if (nodeList[0].Attributes["引号"].Value == "1")
        //            {
        //                mark = true;
        //            }

        //            StringBuilder data = new StringBuilder();
        //            data.Append(nodeList[0].Attributes["报文头"].Value.Replace("/r/n", Environment.NewLine)); //!R
        //            foreach (XmlNode item in nodeList[0].ChildNodes)
        //            {
        //                data.Append(item.Attributes["id"].Value); //!W1
        //                string text = dtBox.Rows[0][item.Attributes["dbname"].Value].ToString().Trim();
        //                if (mark) data.Append("\"");
        //                if (DJGHelper.JustChinese(text))
        //                {
        //                    type = text;
        //                    data.Append(DJGHelper.StringToUnicode(text)); //注：如果含中文内容，需转换为Unicode编码
        //                }
        //                else
        //                {
        //                    data.Append(text);
        //                }
        //                data.Append(item.Attributes["tail"].Value); //Kg
        //                if (mark) data.Append("\"");
        //                data.Append(separator); //\r\n
        //            }
        //            data.Append(nodeList[0].Attributes["报文尾"].Value.Replace("/r/n", Environment.NewLine)); //!P
        //            boxPrintInfo = data.ToString();
        //        }
        //        else
        //        {
        //            this.DebugMsg("箱标对应的数据记录为空！", InfoLevel.error);
        //            this.LogError(boxBarcode + "箱标对应的数据记录为空！");
        //            return "";
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        this.LogError(ex.Message, ex);
        //        return "";
        //    }
        //    return boxPrintInfo;
        //}

        /// <summary>
        /// 三龙贴标数据生成
        /// 使用 三龙箱标配置.xml
        /// </summary>
        /// <param name="boxBarcode"></param>
        /// <returns></returns>
        private string GeneralThreeDragonBoxPrintInfoFromXml(string boxBarcode, out string type)
        {
            type = "";
            if (String.IsNullOrEmpty(boxBarcode))
            {
                this.DebugMsg("箱标为空！", InfoLevel.error);
                return "";
            }
            string boxPrintInfo = "";
            string cmdSql = string.Concat(new string[]
               {
                 "select * from tb_saveddata where uid='",
                  boxBarcode,
                  "'"
               });
            try
            {
                DataTable dtBox = SqlSugarHelper.QueryToDataTable<saveddata>(cmdSql);
                if (dtBox != null && dtBox.Rows.Count > 0)
                {
                    string xmlPath = AppDomain.CurrentDomain.BaseDirectory + "config\\三龙箱标配置.xml";
                    XmlDocument xmlDocument = new XmlDocument();
                    XmlReaderSettings settings = new XmlReaderSettings();
                    settings.IgnoreComments = true;
                    XmlReader reader = XmlReader.Create(xmlPath, settings);
                    xmlDocument.Load(reader);
                    XmlNodeList nodeList = xmlDocument.GetElementsByTagName("字段");
                    reader.Close();

                    StringBuilder data = new StringBuilder();
                    data.Append(nodeList[0].Attributes["报文头"].Value.Replace("/r/n", Environment.NewLine)); //!R
                    foreach (XmlNode item in nodeList[0].ChildNodes)
                    {
                        data.Append(item.Attributes["id"].Value); //!W1
                        string text = dtBox.Rows[0][item.Attributes["dbname"].Value].ToString().Trim();
                        if (item.Attributes["dbname"].Value == "型号")
                        {
                            type = text;
                            text = AutoAddPrefixBlank(text);
                        }
                        data.Append(text);
                        data.Append(item.Attributes["tail"].Value); //Kg
                    }
                    data.Append(nodeList[0].Attributes["报文尾"].Value.Replace("/r/n", Environment.NewLine)); //!P
                    boxPrintInfo = data.ToString();
                }
                else
                {
                    this.DebugMsg("箱标对应的数据记录为空！", InfoLevel.error);
                    this.LogError(boxBarcode + "箱标对应的数据记录为空！");
                    return "";
                }
            }
            catch (Exception ex)
            {
                this.LogError(ex.Message, ex);
                return "";
            }
            return boxPrintInfo;
        }
        /// <summary>
        /// 大威贴标数据生成
        /// </summary>
        /// <param name="boxBarcode"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        private string GeneralDWBoxPrintInfoFromXml(string boxBarcode, out string type)
        {
            type = "GBK";
            if (String.IsNullOrEmpty(boxBarcode))
            {
                this.DebugMsg("箱标为空！", InfoLevel.error);
                return "";
            }
            string boxPrintInfo = "";
            string cmdSql = string.Concat(new string[]
               {
                 "select * from tb_saveddata where uid='",
                  boxBarcode,
                  "'"
               });
            try
            {
                DataTable dtBox = SqlSugarHelper.QueryToDataTable<saveddata>(cmdSql);
                if (dtBox != null && dtBox.Rows.Count > 0)
                {
                    string xmlPath = AppDomain.CurrentDomain.BaseDirectory + "config\\大威箱标配置.xml";
                    XmlDocument xmlDocument = new XmlDocument();
                    XmlReaderSettings settings = new XmlReaderSettings();
                    settings.IgnoreComments = true;
                    XmlReader reader = XmlReader.Create(xmlPath, settings);
                    xmlDocument.Load(reader);
                    XmlNodeList nodeList = xmlDocument.GetElementsByTagName("字段");
                    reader.Close();
                    JObject jsonObject = new JObject();

                    // 添加固定属性
                    jsonObject.Add(nodeList[0].Attributes["模板字段"].Value, nodeList[0].Attributes["模板ID"].Value);
                    JObject data = new JObject();
                    // 添加动态数据
                    foreach (XmlNode item in nodeList[0].ChildNodes)
                    {
                        string sParam = item.Attributes["dbname"].Value.ToString().Trim();
                        string sValue = "";
                        if (!string.IsNullOrEmpty(sParam))
                        {
                            sValue = dtBox.Rows[0][sParam].ToString().Trim();
                        }
                        data.Add(item.Attributes["id"].Value, sValue + item.Attributes["tail"].Value.Trim());
                    }

                    jsonObject.Add(nodeList[0].Attributes["内容字段"].Value, data);
                    boxPrintInfo = JsonConvert.SerializeObject(jsonObject);
                }
                else
                {
                    this.DebugMsg("箱标对应的数据记录为空！", InfoLevel.error);
                    this.LogError(boxBarcode + "箱标对应的数据记录为空！");
                    return "";
                }
            }
            catch (Exception ex)
            {
                this.LogError(ex.Message, ex);
                return "";
            }
            return boxPrintInfo;
        }

        private string GeneralDWErrBoxPrintInfoFromXml(string boxBarcode, string boxPrintInfo)
        {
            string xmlPath = AppDomain.CurrentDomain.BaseDirectory + "config\\大威箱标配置.xml";
            XmlDocument xmlDocument = new XmlDocument();
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.IgnoreComments = true;
            XmlReader reader = XmlReader.Create(xmlPath, settings);
            xmlDocument.Load(reader);
            XmlNodeList nodeList = xmlDocument.GetElementsByTagName("字段");
            reader.Close();
            JObject jsonObject = new JObject();

            // 添加固定属性
            jsonObject.Add(nodeList[0].Attributes["模板字段"].Value, nodeList[0].Attributes["模板ID"].Value);
            JObject data = new JObject();
            // 添加动态数据
            foreach (XmlNode item in nodeList[0].ChildNodes)
            {
                string sParam = item.Attributes["dbname"].Value.ToString().Trim();
                string sValue = "";
                if (!string.IsNullOrEmpty(sParam))
                {
                    switch (sParam.Trim())
                    {
                        case "uid":
                            sValue = boxBarcode;
                            break;
                        case "productName":
                            sValue = "异常箱";
                            break;
                    }
                }
                data.Add(item.Attributes["id"].Value, sValue + item.Attributes["tail"].Value.Trim());
            }

            jsonObject.Add(nodeList[0].Attributes["内容字段"].Value, data);
            boxPrintInfo = JsonConvert.SerializeObject(jsonObject);
            return boxPrintInfo;
        }
        /// <summary>
        /// 自动加前缀空格，用于袋标、箱标型号居中
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        private string AutoAddPrefixBlank(string name, int length = 8)
        {
            string result = name;
            if (name.Length < length)
            {
                for (int i = 0; i < (length - name.Length) / 2; i++)
                {
                    result = " " + result;
                }
            }
            return result;
        }

        ///// <summary>
        ///// 上传EAS箱号信息
        ///// </summary>
        ///// <param name="obj"></param>
        //private void ThreadImportEASCartonInfo(object obj)
        //{
        //    string boxBarcode = obj.ToString();
        //    int count = 1;
        //    while (count < 4)
        //    {
        //        try
        //        {
        //            //string result = EASHelper.Import_CartonInfo(boxBarcode);
        //            string result = KingDee.Import_CartonInfo(boxBarcode);
        //            this.LogInfo(result);

        //            if (!result.StartsWith("Err"))
        //            {
        //                this.DebugMsg("上传EAS箱号信息成功" + boxBarcode, InfoLevel.info);
        //                this.LogInfo("上传EAS箱号信息成功" + boxBarcode);
        //                return;
        //            }
        //            else
        //            {
        //                this.DebugMsg("上传EAS箱号信息失败" + boxBarcode + " 重试:" + count, InfoLevel.warring);
        //                this.DebugMsg("重试计数:" + count + " 失败原因:" + result, InfoLevel.error);
        //                count++;
        //                int timestamp = result.Contains("未能解析此远程") ? 10000 : 3000;
        //                Thread.Sleep(timestamp);
        //            }
        //        }
        //        catch (WebException we)
        //        {
        //            count++;
        //            this.DebugMsg("上传EAS箱号信息出错 " + we.Message, InfoLevel.error);
        //            this.LogError("上传EAS箱号信息出错 " + we.Message);
        //            Thread.Sleep(3000);
        //        }
        //        catch (Exception ex)
        //        {
        //            count++;
        //            this.DebugMsg("上传EAS箱号信息出错 " + ex.Message, InfoLevel.error);
        //            this.LogError("上传EAS箱号信息出错 " + ex.Message, ex);
        //            Thread.Sleep(3000);
        //        }

        //    }
        //}


        ///// <summary>
        ///// 上传EAS箱号信息
        ///// </summary>
        ///// <param name="obj"></param>
        //private void ThreadImportEASCartonInfoTest(object obj)
        //{
        //    string boxBarcode = obj.ToString();
        //    int count = 1;
        //    while (count < 4)
        //    {
        //        try
        //        {
        //            string result = EASHelperDebug.Import_CartonInfo(boxBarcode);
        //            this.LogInfo(result);

        //            if (!result.StartsWith("Err"))
        //            {
        //                this.DebugMsg("上传EAS测试箱号信息成功" + boxBarcode, InfoLevel.info);
        //                this.LogInfo("上传EAS测试箱号信息成功" + boxBarcode);
        //                return;
        //            }
        //            else
        //            {
        //                this.DebugMsg("上传EAS测试箱号信息失败" + boxBarcode + " 重试:" + count, InfoLevel.warring);
        //                this.DebugMsg("重试计数:" + count + " 失败原因:" + result, InfoLevel.error);
        //                count++;
        //                Thread.Sleep(3000);
        //            }
        //        }
        //        catch (WebException we)
        //        {
        //            count++;
        //            this.DebugMsg("上传EAS箱号信息出错 " + we.Message, InfoLevel.error);
        //            this.LogError("上传EAS箱号信息出错 " + we.Message);
        //            Thread.Sleep(3000);
        //        }
        //        catch (Exception ex)
        //        {
        //            count++;
        //            this.DebugMsg("上传EAS箱号信息出错 " + ex.Message, InfoLevel.error);
        //            this.LogError("上传EAS箱号信息出错 " + ex.Message, ex);
        //            Thread.Sleep(3000);
        //        }

        //    }
        //}
    }

    //public class Rootobject
    //{
    //    public string lableIdentification { get; set; }
    //    public Data data { get; set; }
    //}

    //public class Data
    //{
    //    public string QRcode { get; set; }
    //    public string code { get; set; }
    //    public string name { get; set; }
    //    public string size { get; set; }
    //    public string weight { get; set; }
    //    public string group { get; set; }
    //}


    //[SugarTable("流水箱号转换表")]
    //public class BoxIdAndWater
    //{
    //    [SugarColumn(IsNullable = false)]
    //    public int water { get; set; }

    //    [SugarColumn(IsNullable = false)]
    //    public string line { get; set; }

    //    [SugarColumn(IsNullable = false)]
    //    public string boxid { get; set; }

    //    [SugarColumn(IsNullable = false)]
    //    public DateTime createTime { get; set; }
    //}
    #endregion
}
